package com.cheng.lesson02;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

//服务端
public class TestServerDemon02 {
    public static void main(String[] args) throws IOException {
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(8888);
        //2.监听客户端的连接
        Socket socket = serverSocket.accept();//阻塞式监听，会一直等待客户端连接
        //3.创建输入流，获取客户端的输入流
        InputStream is = socket.getInputStream();
        //4.输出文件
        FileOutputStream fos = new FileOutputStream(new File("receive1.png"));
        byte[] buffer = new byte[1024];
        int len;
        while((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        //成功接收完文件后通知客户端
        OutputStream os = socket.getOutputStream();
        //服务端这边输出的是一个byte数组类型，所以客户端那边接收要用管道流
        os.write("我已经成功接收文件,可以断开".getBytes());


        fos.close();
        is.close();
        socket.close();
        serverSocket.close();

    }
}

